package cn.itcast.itcaststore.web.servlet;

import cn.itcast.itcaststore.domain.PageBean;
import cn.itcast.itcaststore.service.Impl.IProductService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/ListProductByNameServlet")
public class ListProductByNameServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String currentPage = request.getParameter("currentPage");
        String name = request.getParameter("name");


        String orderByDate="3";

        if (currentPage==null){
            currentPage="1";
        }

        PageBean pageBean = new PageBean();

        pageBean.setCurrentPage(Integer.parseInt(currentPage));
        pageBean.setOrderByDate(Integer.parseInt(orderByDate));
        pageBean.setCategory(name);

        IProductService iProductService = new IProductService();

        List list=iProductService.getListByname(name,pageBean.getCurrentPage(),pageBean.getOrderByDate());

        int totalDate=iProductService.getTotalDateByName(pageBean.getCategory());
        pageBean.setTotalDate(totalDate);

        if (pageBean.getTotalDate()%pageBean.getOrderByDate()==0){
            pageBean.setTotalPage(pageBean.getTotalDate()/pageBean.getOrderByDate());
        }else {
            pageBean.setTotalPage(pageBean.getTotalDate()/pageBean.getOrderByDate()+1);
        }

        request.setAttribute("productList", list);
        request.setAttribute("bean",pageBean );
        request.getRequestDispatcher("/client/product_list_2.jsp").forward(request,response);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
